package top.jfunc.common.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Supplier;

/**
 * 小权限相关接口
 * @author xiongshiyan at 2021/4/12 , contact me with email yanshixiong@126.com or phone 15208384257
 */
public class CacheService {
    private static final Logger logger = LoggerFactory.getLogger(CacheService.class);
    private final Cache cache;

    public CacheService(Cache cache) {
        this.cache = cache;
    }


    public <V> V valueCache(Supplier<String> cacheKeyGetter, Supplier<V> valueGetter, int cacheTimeInSeconds) {
        //缓存未开启，直接获取
        if(!isCacheEnable()){
            return valueGetter.get();
        }
        String cacheKey = cacheKeyGetter.get();
        //先从缓存拿
        V value = cache.get(cacheKey);
        logger.debug("{},{}", cacheKey, value);
        if(null != value){
            return value;
        }
        //拿不到就获取
        value = valueGetter.get();
        logger.debug("{}", value);
        //存入缓存，带缓存时间
        cache.setex(cacheKey, cacheTimeInSeconds, value);
        return value;
    }

    public <V> V hashValueCache(Supplier<String> cacheKeyGetter, String field, Supplier<V> valueGetter, int cacheTimeInSeconds) {
        //缓存未开启，直接获取
        if(!isCacheEnable()){
            return valueGetter.get();
        }
        //先从缓存拿
        String key = cacheKeyGetter.get();
        V value = cache.hget(key,field);
        logger.debug("{},{},{}", key, field, value);
        if(null != value){
            return value;
        }
        //拿不到就获取
        value = valueGetter.get();
        logger.debug("{}", value);
        cache.hset(key, field, value);
        //缓存时间
        cache.expire(key, cacheTimeInSeconds);
        return value;
    }

    protected boolean isCacheEnable(){
        return true;
    }
}
